# Figure 2
# =========

# INTERACTION PLOTS
# =========================
mSent2 <- felm(sentimentscore ~ (fem_r*gender_type3)-gender_type3 | as.factor(`Document ID`), data = dat.sent, weights = dat.sent$weight_n)
mWordcount2 <- felm(wordcount_adj ~ (fem_r*gender_type3)-gender_type3 | as.factor(`Document ID`), data = dat.sent, weights = dat.sent$weight_n)
mRec2 <- felm(pos_rec ~ (fem_r*gender_type3)-gender_type3 | as.factor(`Document ID`), data = dat.m, weights = dat.m$weight_n)
mDur2 <- felm(`Total Days with Reviewer.x` ~ (fem_r*gender_type3)-gender_type3 | as.factor(`Document ID`), data = dat.m, weights = dat.m$weight_n)



# extract coefficient and variance-covariance matrix
models <- list(mRec2, mWordcount2, mSent2, mDur2)
modelnames <- c("recommendation", "wordcount", "sentiment", "duration")

to_plot <- NULL

for(m in 1:length(models)){
  beta.hat <- coef(models[[m]]) 
  cov <- vcov(models[[m]])
  
  z0 <- c(0,1)
  
  var <- c("gender_type3Male", "gender_type3Female")
  
  toplot <- NULL
  plot.margins <- NULL
  for(i in var){
    
    var.i <- paste("fem_r:", i, sep = "")
    
    dy.dx <- beta.hat["fem_r"] + beta.hat[var.i]*z0
    
    se.dy.dx <- sqrt(cov["fem_r", "fem_r"] + z0^2*cov[var.i, var.i] + 2*z0*cov["fem_r", var.i])
    upr <- dy.dx + 1.96*se.dy.dx
    lwr <- dy.dx - 1.96*se.dy.dx
    
    toplot <- cbind(z0, dy.dx, upr, lwr) %>% data.frame() %>% mutate(var = var.i)
    plot.margins <- bind_rows(plot.margins, toplot)
  }
  
  plot.margins <- plot.margins %>% mutate(var = ifelse(z0 == 0, "fem_r:gender_type3Mixed Team", var)) %>% distinct() %>%
    mutate(var = factor(var, levels = c("fem_r:gender_type3Male", "fem_r:gender_type3Mixed Team", "fem_r:gender_type3Female")
                        , labels = c( "Male", "Mixed","Female")
    )) 
  
  plot.margins <- plot.margins %>% mutate(model = modelnames[m])
  
  to_plot <- bind_rows(to_plot, plot.margins)
  # plot
  
}

to_plot <- to_plot %>% mutate(model = factor(model, levels = c("recommendation", "wordcount", "sentiment", "duration")
                                             , labels = c("Non-Reject Recommendation", "Length", "Sentiment", "Duration")
))
ggplot(to_plot, aes(x = var, y = dy.dx, group = 1)) + 
  geom_point(size = 3) + 
  geom_linerange(aes(ymin = lwr, ymax = upr)) + 
  theme_minimal() +
  theme(axis.text.x = element_text(size=20), text = element_text(size=20)) +
  geom_hline(yintercept = 0, col = "red", lty = 2) + 
  labs(x = "", y = "average marginal effect") + 
  facet_wrap(~model, ncol = 2, scales = "free_y")

ggsave("01_results/02_figures/figure2.pdf", width = 12, height = 8)
